/* 
 * Copyright 2005-2010 Samuel Mello
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; version 2 or later of the License.
 * 
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 * 
 */

/*
 * TextSplitPanel.java
 *
 * Created on Apr 13, 2009, 10:11:02 PM
 */

package datasoul.util;

import javax.swing.JOptionPane;
import javax.swing.text.JTextComponent;

import datasoul.config.WindowPropConfig;
import datasoul.serviceitems.text.TextServiceItem;

/**
 *
 * @author samuel
 */
public class TextSplitPanel extends javax.swing.JPanel {

    /**
	 * 
	 */
	private static final long serialVersionUID = -5095605987736730361L;
	private JTextComponent textComp;

    /** Creates new form TextSplitPanel */
    public TextSplitPanel() {
        initComponents();

        if (WindowPropConfig.getInstance().getTextSplitLine().length() > 0){
            txtMaxLenght.setText(WindowPropConfig.getInstance().getTextSplitLine());
            txtMaxLenght.setEnabled(true);
            cbMaxLenght.setSelected(true);
        }

        if (WindowPropConfig.getInstance().getTextSplitSlide().length() > 0){
            txtMaxSlideLines.setText(WindowPropConfig.getInstance().getTextSplitSlide());
            txtMaxSlideLines.setEnabled(true);
            cbMaxSlideLines.setSelected(true);
        }

    }

    public void registerTextArea(JTextComponent textComp){
        this.textComp = textComp;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        cbMaxLenght = new javax.swing.JCheckBox();
        cbMaxSlideLines = new javax.swing.JCheckBox();
        txtMaxSlideLines = new javax.swing.JTextField();
        txtMaxLenght = new javax.swing.JTextField();
        btnSplit = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();

        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("datasoul/internationalize"); // NOI18N
        cbMaxLenght.setText(bundle.getString("SPLIT IN LINES OF")); // NOI18N
        cbMaxLenght.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbMaxLenghtActionPerformed(evt);
            }
        });

        cbMaxSlideLines.setText(bundle.getString("SPLIT IN SLIDES OF")); // NOI18N
        cbMaxSlideLines.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbMaxSlideLinesActionPerformed(evt);
            }
        });

        txtMaxSlideLines.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
        txtMaxSlideLines.setText("5");
        txtMaxSlideLines.setEnabled(false);
        txtMaxSlideLines.setPreferredSize(new java.awt.Dimension(30, 20));
        txtMaxSlideLines.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtMaxSlideLinesFocusLost(evt);
            }
        });
        txtMaxSlideLines.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtMaxSlideLinesKeyTyped(evt);
            }
        });

        txtMaxLenght.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
        txtMaxLenght.setText("40");
        txtMaxLenght.setEnabled(false);
        txtMaxLenght.setPreferredSize(new java.awt.Dimension(30, 20));
        txtMaxLenght.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtMaxLenghtFocusLost(evt);
            }
        });
        txtMaxLenght.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtMaxLenghtKeyTyped(evt);
            }
        });

        btnSplit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/datasoul/icons/v2/stock_view-details.png"))); // NOI18N
        btnSplit.setText(bundle.getString("SPLIT")); // NOI18N
        btnSplit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSplitActionPerformed(evt);
            }
        });

        jLabel2.setText(bundle.getString("CHARACTERS")); // NOI18N

        jLabel1.setText(bundle.getString("LINES")); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(cbMaxLenght)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtMaxLenght, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addGap(24, 24, 24)
                .addComponent(cbMaxSlideLines)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtMaxSlideLines, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(btnSplit)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(cbMaxLenght)
                .addComponent(cbMaxSlideLines)
                .addComponent(txtMaxSlideLines, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(txtMaxLenght, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel2)
                .addComponent(jLabel1)
                .addComponent(btnSplit))
        );
    }// </editor-fold>//GEN-END:initComponents

    public void setBtnSplitVisible(boolean b){
        btnSplit.setVisible(b);
    }

    public String splitText(String original) throws NumberFormatException {


        int maxSlideLines = 0;
        if (cbMaxSlideLines.isSelected()){
            maxSlideLines = Integer.parseInt(txtMaxSlideLines.getText());
        }

        int maxLenght = 0;
        if (cbMaxLenght.isSelected()){
            maxLenght = Integer.parseInt(txtMaxLenght.getText());
        }

        String str0 = original;

        // If needed remove slide breaks
        if ( maxSlideLines > 0 ){
            str0 = str0.replaceAll("\n"+TextServiceItem.SLIDE_BREAK+"\n", "\n");
        }

        // If needed, remove line breaks
        if ( maxLenght > 0 ){
            str0 = str0.replaceAll("\n"+TextServiceItem.SLIDE_BREAK+"\n", "@@"+TextServiceItem.SLIDE_BREAK+"@@");
            str0 = str0.replaceAll("\n"+TextServiceItem.CHORUS_MARK+"\n", "@@"+TextServiceItem.CHORUS_MARK+"@@");
            str0 = str0.replaceAll("\n", " ");
            str0 = str0.replaceAll("@@"+TextServiceItem.CHORUS_MARK+"@@", "\n"+TextServiceItem.CHORUS_MARK+"\n");
            str0 = str0.replaceAll("@@"+TextServiceItem.SLIDE_BREAK+"@@", "\n"+TextServiceItem.SLIDE_BREAK+"\n");
        }

        // if needed, break lines respecting maximum line width
        if (maxLenght > 0){
            StringBuffer sb  = new StringBuffer();
            String tmp;
            int lastspace = 0;
            int lastbreak = 0;
            for (int i=0; i<str0.length(); i++){
                if ( str0.charAt(i) == ' '){
                    lastspace = i;
                }
                if ( (i-lastbreak) >  maxLenght){
                    tmp = str0.substring(lastbreak, lastspace).trim();
                    if (tmp.length() > 0){
                        sb.append(tmp+"\n");
                    }
                    lastbreak = lastspace;
                }
                if (str0.charAt(i) == '\n'){
                    tmp = str0.substring(lastbreak, i).trim();
                    if (tmp.length() > 0){
                        sb.append(tmp+"\n");
                    }
                    lastbreak = i;
                }
            }
            tmp = str0.substring(lastbreak).trim();
            if (tmp.length() > 0){
                sb.append(tmp+"\n");
            }

            str0 = sb.toString();
        }

        // Split in slides
        if (maxSlideLines > 0){
            str0 = str0.replace("\n"+TextServiceItem.SLIDE_BREAK+"\n","\n");

            StringBuffer sb = new StringBuffer();

            String verses[] = str0.split(TextServiceItem.CHORUS_MARK+"\n");
            for (int i=0; i<verses.length; i++){
                String vlines[] = verses[i].split("\n");
                for (int j=0; j<vlines.length; j++){
                    sb.append(vlines[j]);
                    sb.append("\n");
                    if (maxSlideLines != 0 && (j+1)%maxSlideLines == 0 && vlines.length-j>1){
                        sb.append(TextServiceItem.SLIDE_BREAK);
                        sb.append("\n");
                    }
                }
                if (i < verses.length -1){
                    sb.append(TextServiceItem.CHORUS_MARK);
                    sb.append("\n");
                }
            }
            str0 = sb.toString();
        }

        return str0;

    }

    private void btnSplitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSplitActionPerformed

        try{
            String str0 = splitText(textComp.getText());

            // Store the result
            textComp.setText(str0);
        }catch(NumberFormatException ex){
            JOptionPane.showMessageDialog(this,java.util.ResourceBundle.getBundle("datasoul/internationalize").getString("INVALID VALUE"),java.util.ResourceBundle.getBundle("datasoul/internationalize").getString("DATASOUL ERROR"),0);
        }

    }//GEN-LAST:event_btnSplitActionPerformed

    private void txtMaxLenghtKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtMaxLenghtKeyTyped
        if (evt.getKeyChar() < '0' || evt.getKeyChar() > '9') {
            evt.consume();
        }

    }//GEN-LAST:event_txtMaxLenghtKeyTyped

    private void txtMaxSlideLinesKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtMaxSlideLinesKeyTyped
        if (evt.getKeyChar() < '0' || evt.getKeyChar() > '9') {
            evt.consume();
        }
    }//GEN-LAST:event_txtMaxSlideLinesKeyTyped

    private void cbMaxLenghtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbMaxLenghtActionPerformed
        txtMaxLenght.setEnabled(cbMaxLenght.isSelected());
        if (cbMaxLenght.isSelected()){
            WindowPropConfig.getInstance().setTextSplitLine(txtMaxLenght.getText());
        }else{
            WindowPropConfig.getInstance().setTextSplitLine("");
        }

    }//GEN-LAST:event_cbMaxLenghtActionPerformed

    private void cbMaxSlideLinesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbMaxSlideLinesActionPerformed
        txtMaxSlideLines.setEnabled(cbMaxSlideLines.isSelected());
        if (cbMaxSlideLines.isSelected()){
            WindowPropConfig.getInstance().setTextSplitSlide(txtMaxSlideLines.getText());
        }else{
            WindowPropConfig.getInstance().setTextSplitSlide("");
        }
    }//GEN-LAST:event_cbMaxSlideLinesActionPerformed

    private void txtMaxLenghtFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtMaxLenghtFocusLost
        if (cbMaxLenght.isSelected()){
            WindowPropConfig.getInstance().setTextSplitLine(txtMaxLenght.getText());
        }else{
            WindowPropConfig.getInstance().setTextSplitLine("");
        }
    }//GEN-LAST:event_txtMaxLenghtFocusLost

    private void txtMaxSlideLinesFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtMaxSlideLinesFocusLost
        if (cbMaxSlideLines.isSelected()){
            WindowPropConfig.getInstance().setTextSplitSlide(txtMaxSlideLines.getText());
        }else{
            WindowPropConfig.getInstance().setTextSplitSlide("");
        }
    }//GEN-LAST:event_txtMaxSlideLinesFocusLost


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnSplit;
    private javax.swing.JCheckBox cbMaxLenght;
    private javax.swing.JCheckBox cbMaxSlideLines;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JTextField txtMaxLenght;
    private javax.swing.JTextField txtMaxSlideLines;
    // End of variables declaration//GEN-END:variables

}


